import { computed, reactive, ref, toValue } from 'vue'
import useLoading from '@/hooks/use-loading.js'

/**
 *
 * @param request 请求方法
 * @param params 查询的额外参数
 * @param postData 获取的数据进行处理
 * @param onLoad 数据加载完成后触发，会多次触发
 * @param onRequestError 数据加载失败时触发
 * @param onLoadingChange loading状态改变时触发
 * @param isPagination 是否分页
 * @param defaultPagerParams 默认分页参数
 */
export default function useTable(
  request,
  params,
  postData,
  onLoad,
  onRequestError,
  onLoadingChange,
  isPagination = true,
  defaultPagerParams,
) {
  // 表格数据
  const tableData = ref([])

  // 分页数据
  const pagination = reactive({
    currentPage: defaultPagerParams?.currentPage ?? 1,
    pageSize: defaultPagerParams?.pageSize ?? 10,
    total: 0,
  })
  const [loading, setLoading] = useLoading(false)

  const pageParam = computed(() => {
    return {
      currentPage: pagination.currentPage,
      pageSize: pagination.pageSize,
    }
  })

  /**
   * 获取表格数据
   */
  const fetchDataList = async () => {
    if (!request) return
    try {
      handleLoading(true)
      // 查询参数和分页参数合并
      const queryParams = {
        ...(params ? toValue(params) : {}),
        ...(isPagination ? toValue(pageParam) : {}),
      }

      // 调用接口
      const { data, total, msg, success } = await request(queryParams)
      if (success === true) {
        tableData.value = postData?.(data) || data
        pagination.total = total ?? data.length
        onLoad?.(tableData)
      } else {
        onRequestError?.(msg)
      }
    } catch (e) {
      onRequestError?.(e)
    } finally {
      handleLoading(false)
    }
  }

  const handleLoading = (val) => {
    setLoading(val)
    onLoadingChange?.(val)
  }

  const handleSizeChange = (val) => {
    pagination.currentPage = 1
    pagination.pageSize = val
    fetchDataList?.()
  }

  const handleCurrentChange = (val) => {
    pagination.currentPage = val
    fetchDataList?.()
  }

  return {
    tableData,
    pagination,
    loading,
    fetchDataList,
    handleSizeChange,
    handleCurrentChange,
  }
}
